﻿using AutoMapper;
using MediatR;
using ProductManagement.Applcation.Command;
using ProductManagement.Domain.ProductsDomain;
using ProductManagement.Infrstructre.Interface;

namespace ProductManagement.Applcation.CommandHanlers
{
    /// <summary>
    /// 产品修改
    /// </summary>
    public class ProductUpdateCommandHandler:IRequestHandler<ProductUpdateCommand,int>
    {
        private readonly InterfaceProductRepository _productRepository;
        private readonly IMapper mapper;

        public ProductUpdateCommandHandler(InterfaceProductRepository productRepository, IMapper mapper)
        {
            _productRepository = productRepository;
            this.mapper = mapper;
        }

        public async Task<int> Handle(ProductUpdateCommand request, CancellationToken cancellationToken)
        {
            var res = (await _productRepository.GetAll()).Where(x=>x.PName==request.dto.PName);
            if (res.Count() == 0)
            {
                var s = (await _productRepository.GetAll()).First(x => x.ProductId == request.dto.ProductId);
                return await _productRepository.UpdateAsync(mapper.Map(request.dto,s));
            }
            else
            {
                return -1;//产品名称重复
            }
        }
    }
}
